package com.tanhua.admin.listener;

import com.alibaba.fastjson.JSON;
import com.itheima.tanhua.domain.Log;
import com.tanhua.admin.mapper.LogMapper;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Lff
 * @date 2022/4/6
 * <p>
 * 日志监听器，处理日志消息
 */
@Component
public class LogListener {

    @Autowired
    private LogMapper logMapper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(
                    value = "tanhua.log.queue",
                    durable = "true"
            ),
            exchange = @Exchange(
                    value = "tanhua.log.exchange",
                    type = ExchangeTypes.TOPIC),
            key = {"log.*"})
    )
    public void logHandler(String msg) {
        try {
            Map map = JSON.parseObject(msg, Map.class);
            String type = map.get("type").toString();
            String userId = map.get("userId").toString();
            String logTime = map.get("logTime").toString();

            //构造Log
            Log log = new Log(Long.valueOf(userId), logTime, type);
            //调用api保存
            logMapper.insert(log);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
}
